import 'package:flutter/cupertino.dart';
import 'package:flutter_base/base/controller/base_controller.dart';
import 'package:flutter_base/pages/test_detail/model/model_test_detail.dart';
import 'package:flutter_base/http/http_export.dart';
import 'package:flutter_base/pages/test_result/model/model_test_result.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:get/get.dart';

class TestResultLogic extends BaseController {
  final int userTestId = Get.arguments?['userTestId'] ?? 0;

  // 测试详情数据
  var testDetail = Rx<ModelTestResult>(ModelTestResult());

  final ScrollController scrollController = ScrollController();
  final RxDouble scrollPosition = 0.0.obs;
  final RxBool isDarkTitle = true.obs;

  // 计算AppBar背景透明度 (0-1)
  double get appBarOpacity => (scrollPosition.value / 100).clamp(0.0, 1.0);

  @override
  void onInit() {
    super.onInit();

    scrollController.addListener(_onScroll);
  }

// 滚动监听函数
  void _onScroll() {
    scrollPosition.value = scrollController.offset;
    // 更新标题颜色状态（滚动超过50时变为深色）
    isDarkTitle.value = scrollController.offset <= 50;
  }

  @override
  void onClose() {
    // 释放滚动控制器
    scrollController.removeListener(_onScroll);
    scrollController.dispose();
    super.onClose();
  }

  @override
  void onReady() {
    super.onReady();
    // 加载测试结果数据
    executeInitMethod(loadTestResult);
  }

  // 加载测试结果
  Future<void> loadTestResult() async {
    HttpResponse response = await HttpManager().get(
      API.testUserDetail,
      params: {'id': userTestId},
      fromJson: ModelTestResult.fromJson,
      uiType: HttpUIType.none, // 因为已经在页面上显示了加载状态
    );

    if (response.isSuccess) {
      testDetail.value = response.data;
      // testDetail.value.result?.components?.insert(
      //     0,
      //     ModelTestResultResultComponents(data: {
      //       "result_type": "Personality Type",
      //       "result_value": "ENFP",
      //       "result_title": "The Campaigner",
      //       "result_desc": "Enthusiastic, creative and sociable free spirits",
      //       "result_image": "url"
      //     }, type: 'MatchingResultBlock'));
      //
      // testDetail.value.result?.components?.insert(
      //     0,
      //     ModelTestResultResultComponents(data: {
      //       "title": "Personality Trait Analysis",
      //       "dimensions": [
      //         {
      //           "name": "Extraversion",
      //           "value": 75,
      //           "desc": "Source of social energy"
      //         }
      //       ],
      //       "max_value": 100
      //     }, type: 'RadarChartBlock'));
      doFinished();
    } else {
      doError('获取测试结果失败');
    }
  }

  // 返回首页
  void backToHome() {
    // Get.offAllNamed('/main');
  }

  // 重新测试
  void retakeTest() {
    // Get.offNamed('/testDetail', arguments: {'testId': testId});
  }
}
